<template>
  <div class="charts-section">
    <div class="section-header">
      <h3>数据分析</h3>
    </div>

    <el-row :gutter="16">
      <!-- 主要参数趋势图 -->
      <el-col :span="16">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>主要参数趋势</span>
            <div class="chart-legend">
              <el-checkbox-group v-model="localSelectedMetrics" @change="handleMetricsChange">
                <el-checkbox label="power">功率</el-checkbox>
                <el-checkbox label="voltage">电压</el-checkbox>
                <el-checkbox label="current">电流</el-checkbox>
                <el-checkbox label="temperature">温度</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <div id="mainTrendChart" style="height: 400px;" v-loading="chartLoading"></div>
        </el-card>
      </el-col>

      <!-- 能耗分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header">
            <span>能耗分布</span>
          </div>
          <div id="energyDistributionChart" style="height: 400px;" v-loading="chartLoading"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" style="margin-top: 16px;">
      <!-- 设备效率分析 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>设备效率分析</span>
          </div>
          <div id="efficiencyChart" style="height: 300px;" v-loading="chartLoading"></div>
        </el-card>
      </el-col>

      <!-- 负载分析 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>负载分析</span>
          </div>
          <div id="loadAnalysisChart" style="height: 300px;" v-loading="chartLoading"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { parseTime } from '@/utils/ruoyi';

export default {
  name: "MonitorCharts",
  props: {
    chartTimeRange: {
      type: String,
      default: '1h'
    },
    selectedMetrics: {
      type: Array,
      default: () => ['power', 'voltage', 'current']
    },
    chartLoading: {
      type: Boolean,
      default: false
    },
    queryParams: {
      type: Object,
      default: () => ({})
    },
    deviceList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      localSelectedMetrics: [],
      charts: {
        mainTrend: null,
        energyDistribution: null,
        efficiency: null,
        loadAnalysis: null
      }
    };
  },
  watch: {
    selectedMetrics: {
      handler(newVal) {
        this.localSelectedMetrics = [...newVal];
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    this.disposeCharts();
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    parseTime,
    handleMetricsChange() {
      this.$emit('metrics-change', this.localSelectedMetrics);
    },
    initCharts() {
      this.$nextTick(() => {
        try {
          // 主要参数趋势图
          const mainTrendElement = document.getElementById('mainTrendChart');
          if (mainTrendElement) {
            console.log('主要参数趋势图容器尺寸:', {
              width: mainTrendElement.offsetWidth,
              height: mainTrendElement.offsetHeight,
              display: window.getComputedStyle(mainTrendElement).display
            });
            this.charts.mainTrend = echarts.init(mainTrendElement);
            console.log('主要参数趋势图初始化成功');

            // 测试图表是否能正常工作
            this.testChart(this.charts.mainTrend, '主要参数趋势图');
          } else {
            console.error('找不到主要参数趋势图容器元素');
          }

          // 能耗分布图
          const distributionElement = document.getElementById('energyDistributionChart');
          if (distributionElement) {
            console.log('能耗分布图容器尺寸:', {
              width: distributionElement.offsetWidth,
              height: distributionElement.offsetHeight,
              display: window.getComputedStyle(distributionElement).display
            });
            this.charts.energyDistribution = echarts.init(distributionElement);
            console.log('能耗分布图初始化成功');
          } else {
            console.error('找不到能耗分布图容器元素');
          }

          // 设备效率分析图
          const efficiencyElement = document.getElementById('efficiencyChart');
          if (efficiencyElement) {
            this.charts.efficiency = echarts.init(efficiencyElement);
            console.log('设备效率分析图初始化成功');
          } else {
            console.error('找不到设备效率分析图容器元素');
          }

          // 负载分析图
          const loadAnalysisElement = document.getElementById('loadAnalysisChart');
          if (loadAnalysisElement) {
            this.charts.loadAnalysis = echarts.init(loadAnalysisElement);
            console.log('负载分析图初始化成功');
          } else {
            console.error('找不到负载分析图容器元素');
          }

          // 添加窗口大小变化监听
          this.handleResize();
        } catch (error) {
          console.error('图表初始化失败:', error);
        }
      });
    },

    // 测试图表是否能正常工作
    testChart(chart, name) {
      if (!chart) return;

      try {
        const testOption = {
          title: {
            text: name + ' - 测试',
            left: 'center'
          },
          xAxis: {
            type: 'category',
            data: ['测试1', '测试2', '测试3']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [10, 20, 30],
            type: 'line'
          }]
        };

        chart.setOption(testOption);
        console.log(name + '测试图表设置成功');

        // 3秒后清除测试图表
        setTimeout(() => {
          chart.clear();
          console.log(name + '测试图表已清除');
        }, 3000);
      } catch (error) {
        console.error(name + '测试图表失败:', error);
      }
    },
    disposeCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.dispose();
        }
      });
    },
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    },
    updateMainTrendChart(data) {
      if (!this.charts.mainTrend) {
        console.warn('主趋势图表未初始化');
        return;
      }

      // 如果没有数据，显示空状态
      if (!data || data.length === 0) {
        console.warn('图表数据为空，显示空状态');
        const emptyOption = {
          title: {
            text: '主要参数趋势',
            left: 'center',
            textStyle: { fontSize: 16 }
          },
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无数据',
              fontSize: 16,
              fill: '#999'
            }
          }
        };
        this.charts.mainTrend.setOption(emptyOption, true);
        return;
      }

      console.log('原始图表数据:', data);

      // 数据格式转换：后端返回的字段映射到前端期望的字段
      const transformedData = data.map(item => {
        // 处理时间字段
        const timestamp = item.ts || item._wstart || item.time_point;

        return {
          ts: timestamp,
          // 功率数据：优先使用avg_power，回退到power
          power: item.avg_power || item.power || 0,
          // 电压数据：如果没有则使用默认值（实际项目中应该从其他API获取）
          voltage: item.voltage || 220,
          // 电流数据：如果没有则使用默认值
          current: item.current || (item.avg_power || item.power || 0) / 220 * 1000, // 简单估算
          // 温度数据：如果没有则使用默认值
          temperature: item.temperature || 25,
          // 保留原始数据用于调试
          _original: item
        };
      });

      console.log('转换后的图表数据:', transformedData);

      const times = transformedData.map(item => this.parseTime(item.ts, '{m}-{d} {h}:{i}'));
      const series = [];

      if (this.localSelectedMetrics.includes('power')) {
        series.push({
          name: '功率(kW)',
          type: 'line',
          data: transformedData.map(item => Number(item.power).toFixed(2)),
          smooth: true,
          lineStyle: { color: '#409EFF' },
          symbol: 'circle',
          symbolSize: 4
        });
      }

      if (this.localSelectedMetrics.includes('voltage')) {
        series.push({
          name: '电压(V)',
          type: 'line',
          yAxisIndex: 1,
          data: transformedData.map(item => Number(item.voltage).toFixed(1)),
          smooth: true,
          lineStyle: { color: '#67C23A' },
          symbol: 'circle',
          symbolSize: 4
        });
      }

      if (this.localSelectedMetrics.includes('current')) {
        series.push({
          name: '电流(A)',
          type: 'line',
          data: transformedData.map(item => Number(item.current).toFixed(2)),
          smooth: true,
          lineStyle: { color: '#E6A23C' },
          symbol: 'circle',
          symbolSize: 4
        });
      }

      if (this.localSelectedMetrics.includes('temperature')) {
        series.push({
          name: '温度(℃)',
          type: 'line',
          yAxisIndex: 1,
          data: transformedData.map(item => Number(item.temperature).toFixed(1)),
          smooth: true,
          lineStyle: { color: '#F56C6C' },
          symbol: 'circle',
          symbolSize: 4
        });
      }

      console.log('图表系列数据:', series);

      const option = {
        title: {
          text: '主要参数趋势',
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(param => {
              result += param.marker + param.seriesName + ': ' + param.value + '<br/>';
            });
            return result;
          }
        },
        legend: {
          data: series.map(s => s.name),
          bottom: 10
        },
        grid: {
          left: '8%',
          right: '8%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: times,
          axisLabel: {
            rotate: 45,
            fontSize: 12
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '功率(kW)/电流(A)',
            position: 'left',
            axisLabel: {
              fontSize: 12
            }
          },
          {
            type: 'value',
            name: '电压(V)/温度(℃)',
            position: 'right',
            axisLabel: {
              fontSize: 12
            }
          }
        ],
        series: series,
        animation: true,
        animationDuration: 1000
      };

      console.log('设置图表选项:', option);
      try {
        this.charts.mainTrend.setOption(option, true);
        // 强制重新渲染
        this.$nextTick(() => {
          this.charts.mainTrend.resize();
        });
      } catch (error) {
        console.error('设置图表选项失败:', error);
      }
    },
    updateEnergyDistributionChart(data) {
      if (!this.charts.energyDistribution) {
        console.warn('能耗分布图表未初始化');
        return;
      }

      if (!data || data.length === 0) {
        console.warn('能耗分布数据为空');
        // 显示空数据提示
        this.charts.energyDistribution.setOption({
          title: {
            text: '能耗分布',
            left: 'center',
            textStyle: { fontSize: 16 }
          },
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无数据',
              fontSize: 14,
              fill: '#999'
            }
          }
        });
        return;
      }

      console.log('原始能耗分布数据:', data);

      const chartData = data.map(item => ({
        name: item.energyType || item.deviceName || item.name || '未知',
        value: Number(item.totalEnergy || item.energy || item.value || 0)
      })).filter(item => item.value > 0); // 过滤掉0值数据

      console.log('转换后的能耗分布数据:', chartData);

      if (chartData.length === 0) {
        console.warn('过滤后的能耗分布数据为空');
        return;
      }

      const option = {
        title: {
          text: '能耗分布',
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} kWh ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: chartData.map(item => item.name)
        },
        series: [
          {
            name: '能耗分布',
            type: 'pie',
            radius: ['20%', '60%'],
            center: ['60%', '50%'],
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: true,
              formatter: '{b}: {d}%'
            }
          }
        ]
      };

      console.log('设置能耗分布图表选项:', option);
      this.charts.energyDistribution.setOption(option, true);
    },
    updateEfficiencyChart(data) {
      if (!this.charts.efficiency) {
        console.warn('设备效率分析图表未初始化');
        return;
      }

      console.log('原始效率分析数据:', data);

      // 如果没有数据，显示空图表
      if (!data || data.length === 0) {
        console.log('效率分析数据为空');
        return;
      }

      const chartData = data;

      const option = {
        title: {
          text: '设备效率分析',
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c}%'
        },
        xAxis: {
          type: 'category',
          data: chartData.map(item => this.parseTime(item.time, '{h}:{i}'))
        },
        yAxis: {
          type: 'value',
          name: '效率(%)',
          min: 0,
          max: 100
        },
        series: [
          {
            name: '效率',
            type: 'bar',
            data: chartData.map(item => Number(item.efficiency).toFixed(1)),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      };

      console.log('设置效率分析图表选项:', option);
      this.charts.efficiency.setOption(option, true);
    },
    updateLoadAnalysisChart(data) {
      if (!this.charts.loadAnalysis) {
        console.warn('负载分析图表未初始化');
        return;
      }

      console.log('原始负载分析数据:', data);

      // 如果没有数据，显示空图表
      if (!data || data.length === 0) {
        console.log('负载分析数据为空');
        return;
      }

      const chartData = data;

      const option = {
        title: {
          text: '负载分析',
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c}%'
        },
        xAxis: {
          type: 'category',
          data: chartData.map(item => this.parseTime(item.time, '{h}:{i}'))
        },
        yAxis: {
          type: 'value',
          name: '负载率(%)',
          min: 0,
          max: 100
        },
        series: [
          {
            name: '负载率',
            type: 'line',
            data: chartData.map(item => Number(item.loadRate).toFixed(1)),
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(255, 158, 68, 0.3)' },
                { offset: 1, color: 'rgba(255, 158, 68, 0.1)' }
              ])
            },
            lineStyle: { color: '#ff9e44' },
            smooth: true
          }
        ]
      };

      console.log('设置负载分析图表选项:', option);
      this.charts.loadAnalysis.setOption(option, true);
    }
  }
};
</script>

<style lang="scss" scoped>
.charts-section {
  margin-bottom: 24px;

  .section-header {
    margin-bottom: 16px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .chart-card {
    margin-bottom: 16px;

    ::v-deep .el-card__header {
      padding: 16px 20px;
      border-bottom: 1px solid #EBEEF5;

      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .chart-legend {
          .el-checkbox-group {
            .el-checkbox {
              margin-right: 16px;

              .el-checkbox__label {
                font-size: 14px;
              }
            }
          }
        }
      }
    }

    ::v-deep .el-card__body {
      padding: 20px;
    }
  }
}
</style>
